<template>
    <div class="goods-info-wrapper" v-if="hasGoodsInfo">
      <div class="goods-info">
        <!-- 店铺信息 -->
        <div class="shop-name" :class="{ 'shop-name__padding-bottom': isCart && !virtualList.length }">
          <i class="iconfont icon-shop_icon"></i>
          <span class="shop-name">{{ appInfo.shop_name }}</span>
        </div>
        <template v-if="hasGoodsInfo">
          <div class="goods-wrapper" v-if="!isCart">
            <!-- 商品主图 -->
            <div class="goods-thumbnail">
              <xe-image class="customClass" v-if="goodsImgSrc" :src="goodsImgSrc" fit="blur" />
              <!-- 商品类型 -->
              <van-tag type="primary" class="goods-type ET tag" color="rgba(51, 51, 51, 0.6)" v-if="showTagType">
                {{ goodsTag }}
              </van-tag>
              <!-- 超级会员标签 -->
              <svip-tag :showSvipTag="useSvipPrice"></svip-tag>
            </div>
            <div class="goods-detail">
              <div class="goods-header">
                <div class="goods-titles">
                  <div class="goods-title">
                    <van-tag type="primary" plain class="goods-tag ET tag" color="#1472FF" v-if="goodsTitleTag">
                      {{ goodsTitleTag }}
                    </van-tag>
                    {{ goodsInfo.goods_name }}
                  </div>
                </div>
                <!-- 称重退补差价提示 -->
                <WeighRefundDescription v-if="goodsInfo.nonstandard_param && goodsInfo.nonstandard_param.is_refund_tips" :is_refund_msg="goodsInfo.nonstandard_param.is_refund_msg" :is_refund_tips="goodsInfo.nonstandard_param.is_refund_tips" />
                <div class="goods-specification ET0" v-if="specification">{{ specification }}</div>
                <div class="goods-expire-desc ET0"
                  v-if="isExpireDisplay && expireDesc && expireDesc !== t('combined_long')">
                  {{ t('goodsInfo_validity') }}：{{ expireDesc }}
                </div>
              </div>
              <div class="goods-quantity ET0">
                <div class="goods-pay-info">
                  <div class="goods-limit" v-if="showStepper">
                    <span class="border-blue" v-if="goodsInfo.sku_info && goodsInfo.sku_info.sku_min_purchase > 1">
                      {{ goodsInfo.sku_info.sku_min_purchase }}{{t('goodsInfo_start_sale')}}
                    </span>
                    <span class="border-orange" v-if="limit_purchase">{{ t('goodsInfo_purchase_limit') }}{{ limit_purchase }}件</span>
                  </div>
                  <div class="goods-price">
                    <span v-if="!integralPrice">{{ goodsPrice | toPrice }}</span>
                    <span v-else>{{ integralPrice }}</span>
                    <span v-if="goodsInfo.is_best === 2" class="sale-unit">/{{ getSaleunit(goodsInfo) }}</span>
                    <div class="goods-tags">
                      <div class="goods-tag marketing-tag channel-auxiliary-bg channel-main-font"
                        v-if="marketingTag && !useSvipPrice">
                        {{ marketingTag }}
                      </div>
                      <div class="goods-tag send-friend" v-if="sendFriend">{{ t('goodsInfo_for_friends') }}</div>
                    </div>
                  </div>
                </div>
                <div class="goods-counter">
                  <van-stepper class="goods-selector" ref="stepper" v-model="count" v-if="showStepper" :max="maxCount"
                    :min="minCount" integer @blur="countBlur" @plus="countChange" @minus="countChange"
                    @overlimit="overlimit" />
                  <div class="goods-count" v-else>x{{ count }}</div>
                </div>
              </div>
            </div>
          </div>
          <div class="goods-list" v-if="isCart && virtualList.length">
            <cart-goods-info v-for="goodsInfo in virtualList" :key="goodsInfo.id" :goodsInfo="goodsInfo">
            </cart-goods-info>
            <goods-pay-detail :goodsCount="virtualInfo.count" :goods_price_total="virtualInfo.totalPrice">
            </goods-pay-detail>
          </div>
        </template>
        <!-- 套餐组件 -->
        <goods-commerce class="goods-commerce" :resSkuStock="1" :goodsInfo="goodsInfo" :packageInfo="packageInfo"
          v-if="!(isCart || baseInfo.isIntegral || isCop || isEco) && !!packageInfo">
        </goods-commerce>
        <CCombinedGoodsList v-if="isCop" :spuId="goodsInfo.spu_id" :skuId="goodsInfo.sku_info && goodsInfo.sku_info.sku_id"></CCombinedGoodsList>
      </div>
      <div class="goods-info" v-if="isCart && entityList.length">
        <div class="goods-list">
          <cart-goods-info v-for="goodsInfo in entityList" :key="goodsInfo.id" :goodsInfo="goodsInfo"></cart-goods-info>
          <goods-pay-detail :goodsCount="entityInfo.count" :goods_price_total="entityInfo.totalPrice"></goods-pay-detail>
        </div>
      </div>
    </div>
  </template>

  <script>
  import { replaceCDN } from "@xiaoe/js-tools/lib/replaceCDN";
  import { isEmptyObject } from "../../utils/index";
  import {
    RESOURCE_TYPES_MAP,
    ENTITY_GOODS,
    MARKETING_LIMIT_DISCOUNT,
    MARKETING_SEC_KILL,
    OFFLINE_CLASS,
    OLC_TYPE,
    RESOURCE_TYPES,
    SVIP_SPU_TYPE,
    VALUE_COUPON,
    SERVICE_GOODS,
    ACTIVITY_MANAGE,
    E_COURSE,
    COP_GOODS
  } from "../../utils/constants";
  import { isMP, isEcommunityApp } from "../../utils/checkEnv";
  import SvipTag from "./SvipTag";
  import CartGoodsInfo from "./CartGoodsInfo";
  import GoodsPayDetail from "./GoodsPayDetail";
  import { Stepper, Tag } from "vant";
  import { Image as XeImage } from '@xiaoe/vant';
  import locale from "../../../../mixins/locale";
  import GoodsCommerce from '../GoodsCommerce';
  import WeighRefundDescription from './WeighRefundDescription';
  import Mimir from "@xiaoe/mimir";

  export default {
    name: 'GoodsInfo',
    mixins: [locale],
    props: {
      baseInfo: {
        type: Object,
        default: () => ({})
      },
      goodsInfo: {
        type: Object,
        default: () => ({})
      },
      cartGoodsList: {
        type: Array,
        default: () => []
      },
      confirmDetail: {
        type: Object,
        default: () => ({})
      },
      isCart: {
        type: Boolean,
        default: false
      },
      svipInfo: {
        type: Object,
        default: () => ({})
      },
      marketingData: {
        type: Object,
        default: () => ({})
      },
      businessConf: {
        type: Object,
        default: () => ({})
      },
      periodIsGray: {
        type: Boolean,
        default: false
      },
      cartInfo: {
        type: Object,
        default: () => ({})
      },
      formData: {
        type: Object,
        default: () => ({})
      },
      //赠品信息
      packageInfo: {
        type: Object
      }
    },
    data() {
      return {
        goodsCount: 1
      };
    },
    components: {
      SvipTag,
      [Stepper.name]: Stepper,
      [Tag.name]: Tag,
      CartGoodsInfo,
      GoodsPayDetail,
      // GoodsCommerce: () => import(/* webpackChunkName: "GoodsCommerce" */'@/views/goods_detail/components/GoodsCommerce'),
      GoodsCommerce,
      CCombinedGoodsList: () => Mimir({ section: 'jingwei',project:'live_h5' }).get("c-combined-goods-list"), // 组合商品
      XeImage,
      WeighRefundDescription
    },
    filters: {
      toPrice(value) {
        return `￥${((value || 0) / 100).toFixed(2)}`;
      },
    },
    mounted() {
      this.initStepper();
      console.log(")))))))))))))))))",this.confirmDetail)
    },
    computed: {
      isCop(){
        return this.goodsInfo.spu_type === COP_GOODS
      },
      isEco () {
        return isEcommunityApp
      },
      virtualList() {
        return this.cartInfo?.data?.virtualList;
      },
      virtualInfo() {
        return this.cartInfo?.data?.virtualInfo;
      },
      entityList() {
        return this.cartInfo?.data?.entityList;
      },
      entityInfo() {
        return this.cartInfo?.data?.entityInfo;
      },
      historyBuy() {
        return this.goodsInfo.has_buy_num
      },
      isServiceGoods() {
        return this.goodsInfo.spu_type === SERVICE_GOODS
      },
      minCount() {
        return this.goodsInfo.sku_info?.sku_min_purchase || 1;
      },
      maxCount() {
        // 下面三个判断语句都是判断活动的库存限购
        // 商品限购要跟库存对比。
        var maxCount = 0
        if (this.isTeam) {
          if (this.marketingData && this.marketingData.can_buy_num >= 0) {
            maxCount = this.marketingData.can_buy_num;
          }
        }
        if (this.isDiscounted) {
          if (this.marketingData && this.marketingData.now_stock > 0 && this.marketingData.all_stock > 0) {
            maxCount = this.marketingData.now_stock
          }
        }
        if (this.isSecKill) {
          if (this.marketingData && this.marketingData.event_has_stock && this.marketingData.event_stocks_left > 0) {
            maxCount = this.marketingData.event_stocks_left
          }
        }
        if (this.sendFriend) {
          return 1000
        }
        if (this.baseInfo.isIntegral) {
          return this.$route.query.user_able_redeem_number
        }
        //设置了限购
        if (maxCount === 0 || maxCount > this.goodsInfo.stock) {
          maxCount = this.goodsInfo.stock
        }

        if (this.goodsInfo.limit_purchase) {
          // 限购模式 - 3 - 按单限购，不需要计算已够
          if (this.goodsInfo.limit_type && this.goodsInfo.limit_type === 3){
            return this.goodsInfo.limit_purchase
          }else{
            let count = this.goodsInfo.limit_purchase - (this.goodsInfo.has_buy_num || 0)
            count < 0 ? count = 0 : count
            return count < maxCount ? count : maxCount
          }
        } else if (this.isServiceGoods) {
          const backendLimit = 1000 // 服务类商品正常情况下单次限购1000个
          return maxCount < backendLimit ? maxCount : backendLimit
        } else {
          return maxCount
        }
      },
      count: {
        get() {
          const url = location.href
          const count = Number(this.getUrlParam(url, 'count'))
          const minCount = Number(this.minCount)
          if(count > minCount ) {
            return count
          } else {
            return (this.goodsCount != 1) ? this.goodsCount : (this.formData.count || 1);
          }
        },
        set(count) {
          if (count <= 0) {
            count = 1;
          }
          if (count === 1000 && this.sendFriend) {
            sessionStorage.setItem('toastWarn', true)
          }

          this.goodsCount = Number(count);
          this.countChange();
        }
      },
      marketingTag() {
        if (this.isDiscounted) {
          return this.t('goodsInfo_limit_discounts');
        } else if (this.isTeam) {
          return this.t('goodsInfo_group_buy');
        } else if (this.isSecKill) {
          if (this.noSubscribe) {
            return ''
          }
          return this.t('goodsInfo_seckill')
        }
        return ''
      },
      goodsPrice() {
        if (this.useSvipPrice) {
          return this.svipPrice;
        }
        // 有营销信息，优先取营销价格
        if (this.marketingPrice) {
          return this.marketingPrice;
        }

        return this.goodsInfo.piece_price;
      },
      integralPrice() {
        return this.baseInfo.isIntegral ? `${this.baseInfo.pointsNum} ${this.t('payDetail_points')}` : ''
      },
      limit_purchase() {
        if (this.isTeam) {
          if (this.marketingData && this.marketingData.can_buy_num > 0) {
            return this.marketingData.can_buy_num;
          }
          return 0
        } else {
          return this.goodsInfo.limit_purchase
        }
      },
      // 是否送好友下单
      sendFriend() {
        if (this.baseInfo.isSendFriend) {
          return true;
        }
        return false;
      },
      showStepper() {
        let spuTypes = [ENTITY_GOODS, VALUE_COUPON, SERVICE_GOODS, ACTIVITY_MANAGE]
        return (spuTypes.includes(this.goodsInfo.spu_type) || this.sendFriend) && !this.goodsInfo.is_goods_package;
      },
      expireDesc() {
        return this.goodsInfo.sku_info && this.goodsInfo.sku_info.expire_info && this.goodsInfo.sku_info.expire_info.expire_desc
      },
      isExpireDisplay() {
        return this.goodsInfo.sku_info && this.goodsInfo.sku_info.expire_info && this.goodsInfo.sku_info.expire_info.is_expire_display
      },
      spuType() {
        return this.goodsInfo?.spu_type || '';
      },
      // 当前商品类型是否是会员
      isMMB() {
        return this.spuType === RESOURCE_TYPES_MAP.MEMBER;
      },
      specification() {
        return this.goodsInfo?.attr_value?.attr_value
      },
      goodsTitleTag() {
        return this.OLCConf && OLC_TYPE[this.OLCConf.teaching_model];
      },
      OLCConf() {
        return this.businessConf[OFFLINE_CLASS];
      },
      hasGoodsInfo() {
        return !isEmptyObject(this.goodsInfo) || this.cartGoodsList.length;
      },
      // 店铺信息
      appInfo() {
        if (this.confirmDetail?.app_info) {
          return this.confirmDetail?.app_info;
        }
        if (this.cartInfo?.shop_info) {
          return this.cartInfo.shop_info;
        }
        return {};
      },
      goodsImgSrc() {
        if (Array.isArray(this.goodsInfo.goods_img)) {
          return this.goodsInfo.goods_img[0];
        }
        return replaceCDN(this.goodsInfo.goods_img, { width: 400 })
      },
      showTagType() {
        let showTag = [RESOURCE_TYPES_MAP.ENTITY_GOODS, RESOURCE_TYPES_MAP.VALUE_COUPON, RESOURCE_TYPES_MAP.SERVICE_GOODS, RESOURCE_TYPES_MAP.ASSOCIATION, RESOURCE_TYPES_MAP.ALIVE];
        if (showTag.includes(this.spuType)) {
          if (this.goodsInfo.goods_tag_is_show === 1) {
            return true;
          } else {
            return false;
          }
        } else {
          return true;
        }
      },
      goodsTag() {
        return (this.goodsInfo.spu_type == E_COURSE || this.baseInfo.spu_type == E_COURSE || this.goodsInfo?.sell_mode == 2)
          ? this.t('spuType_training_pro')
          : (this.goodsInfo.goods_tag || RESOURCE_TYPES[this.baseInfo.spu_type] || RESOURCE_TYPES[this.goodsInfo.spu_type]);
      },
      supportSvip() {
        return SVIP_SPU_TYPE.includes(this.goodsInfo.spu_type);
      },
      useSvipPrice() {
        return this.supportSvip && this.svipPrice >= 0 && (this.svipPrice < this.marketingPrice || !this.marketingPrice) && !this.baseInfo.isSendFriend && !this.baseInfo.isIntegral;
      },
      // 超级会员价
      svipPrice() {
        let skuPriceInfo = this.svipInfo.sku_svip_price_list;
        //超级会员接入统一商品对拼团下单时特殊处理忽略超级会员价
        if (skuPriceInfo && this.isSvip && !this.isTeam) {
          return skuPriceInfo[this.baseInfo.sku];
        }
        return '--';
      },
      isSvip() {
        if (this.svipInfo.svip_info && this.svipInfo.svip_info.user_svip_info) {
          return this.svipInfo.svip_info.user_svip_info.state === 1;
        }
        return false;
      },
      // 营销价格
      marketingPrice() {
        if (this.marketingData && this.joinMarketingActivity) {
          if (this.noSubscribe) {
            return 0
          }
          let skuInfo = (this.marketingData.specs_info || []).find((specs) => {
            if (this.goodsInfo.resource_type == 4) return specs.specs_id === this.goodsInfo.resource_id
            return specs.specs_id === this.baseInfo.sku;
          }) || {};
          if (skuInfo.stage_prices && this.baseInfo.step) {
            let step = Number(this.baseInfo.step);
            if (skuInfo.stage_prices[step]) {
              return skuInfo.stage_prices[step].member;
            }
          }

          return skuInfo.price || this.marketingData.low_price;
        }
        return 0;
      },
      // 是否参与了营销活动
      joinMarketingActivity() {
        return this.isDiscounted || this.isTeam || this.isSecKill;
      },
      isDiscounted() {
        return this.marketingData.activity_type === MARKETING_LIMIT_DISCOUNT;
      },
      isSecKill() {
        return this.marketingData.activity_type === MARKETING_SEC_KILL && this.marketingData.in_activity === 1 && this.marketingData.event_has_stock === 1;
      },
      // 是否参加拼团
      isTeam() {
        return !isEmptyObject(this.marketingData) && this.baseInfo.isTeam;
      },
      // 如果是秒杀但没有预约
      noSubscribe() {
        return this.isSecKill && this.marketingData.is_subscribe === 1 && this.marketingData.user_subscribed === 0
      },
    },
    methods: {
      getUrlParam (url, paramName) {
        const searchParams = new URLSearchParams(new URL(url).search);
        return searchParams.get(paramName);
      },
      listenStepperInputChange() {
        if (this.$refs.stepper) {
          this.$refs.stepper.$refs.input.addEventListener('change', () => {
            this.countBlur();
          })
        }
      },
      initStepper() {
        // 抛出count初始值
        this.goodsCount = Number(this.count);
        this.countBlur(true);
        this.listenStepperInputChange()
      },
      countChange() {
        this.$nextTick(() => {
          this.countBlur();
        })
      },
      /**
        * init 是否初次触发
        */
      countBlur(init) {
        // if (this.count === this.goodsCount && init !== true) {
        //   return false;
        // }
        let count = this.goodsCount;
        if (count > this.maxCount && this.maxCount > 0) {
          count = this.maxCount;
        }

        if (isMP && init) {
          // 商品数量
          let goodsInfo = JSON.parse(localStorage.getItem('goodsInfo'));
          goodsInfo && goodsInfo.prePayParams && (count = goodsInfo.prePayParams.count);
        }
        this.$emit('count-change', count,init);
      },
      overlimit(limitType) {
        if (limitType === 'plus') {
          if (this.goodsInfo.stock === this.count || this.count > this.goodsInfo.stock) {
            this.$toast(this.t('goodsInfo_out_stock'));
            return
          }
          if (this.maxCount === this.count) {
            if (this.isTeam && this.maxCount === this.marketingData.can_buy_num) {
              if (this.marketingData.limit_sum === this.count) {
                this.$toast(this.t('goodsInfo_limited_to') + this.maxCount + this.t('goodsInfo_items'))
                return
              }
              this.marketingData.limit_one ? this.$toast(`${this.t('goodsInfo_purchase_limit_per_order')}${this.maxCount}${this.t('goodsInfo_items')}`) : this.$toast(`${this.t('goodsInfo_limited_to')}${this.maxCount}${this.t('goodsInfo_items')}`);
              return
            }
            if (this.sendFriend) {
              return
            }
            this.historyBuy ? this.$toast(`${this.t('goodsInfo_limited_to')}${this.goodsInfo.limit_purchase}${this.t('goodsInfo_items')}${this.t('goodsInfo_already_purchased')}${this.historyBuy}${this.t('goodsInfo_items')}`) : this.$toast(`${this.t('goodsInfo_limited_to')}${this.goodsInfo.limit_purchase}${this.t('goodsInfo_items')}`);
          }
          if (this.maxCount < this.count) {
            this.historyBuy ? this.$toast(`${this.t('goodsInfo_limited_to')}${this.goodsInfo.limit_purchase}${this.t('goodsInfo_items')}${this.t('goodsInfo_already_purchased')}${this.historyBuy}${this.t('goodsInfo_items')}`) : this.$toast(`${this.t('goodsInfo_limited_to')}${this.goodsInfo.limit_purchase}${this.t('goodsInfo_items')}`);
          }
        }
        if (limitType === 'minus') {
          if (this.minCount === this.count || this.minCount > this.count) {
            this.$toast(`${this.t('goodsInfo_product')}${this.minCount}${this.t('goodsInfo_start_sale')}`);
          }
        }
      },
      // 获取销售单位
      getSaleunit(goods_info){
        return JSON.parse(goods_info.sku_info?.sales_unit || '{}')?.sale_unit || '斤';
      }
    },
  };
  </script>

  <style lang="scss" scoped>
  @import "../../assets/styles/global.scss";
  @import "../../assets/styles/common.scss";
  .goods-info-wrapper {
    margin-bottom: 0.18rem;
  }

  .goods-info {
    padding: 0.32rem 0.32rem 0 0.32rem;
    background: #fff;
    margin-bottom: .24rem;

    .shop-name {
      margin-bottom: .24rem;
    }

    .shop-name__padding-bottom {
      padding-bottom: .24rem;
    }
  }

  .skeleton-wrapper {
    margin-top: .32rem;
  }

  .goods-commerce ::deep {
    padding: 0.32rem 0;

    .entity-gift-select {
      padding: 0;
    }
  }

  .icon-shop_icon {
    margin-right: 0.16rem;
    vertical-align: bottom;
  }

  .goods-wrapper {
    display: flex;
    margin-top: 0.32rem;
    padding-bottom: 0.32rem;
  }

  .goods-thumbnail {
    position: relative;
    flex: 0 0 1.8rem;
    height: 1.8rem;
    border-radius: 0.08rem;
    border: 1px solid #e5e5e5;
    overflow: hidden;

    .customClass {
      object-fit: contain;
      width: 100%;
      height: 100%;
    }

    .goods-type {
      position: absolute;
      right: 0.08rem;
      bottom: 0.08rem;
      text-size-adjust: none;
    }
  }

  .tag {
    font-size: 0.2rem;
  }

  .goods-detail {
    flex: 1;
    margin-left: 0.24rem;
    min-height: 1.8rem;
    display: flex;
    flex-direction: column;

    .goods-header {
      flex: 1;
    }

    .goods-titles {
      display: flex;
      line-height: 1.5;

      .goods-tag {
        margin-right: 0.04rem;
        white-space: nowrap;
      }

      .goods-title {
        display: -webkit-box;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 2;
        overflow: hidden;
        word-break: break-word;
      }
    }

    .goods-specification,
    .goods-expire-desc {
      margin-top: 0.12rem;
      color: #999;
      word-break: break-word;
    }

    .goods-quantity {
      display: flex;
      justify-content: space-between;
      align-items: flex-end;
      margin-top: 0.12rem;
      width: 100%;
      color: #999;

      .goods-pay-info {
        flex-grow: 1;
        display: flex;
        flex-direction: column;
      }

      .goods-limit {
        margin-bottom: .16rem;

        .border-blue {
          border: #1472FF .02rem solid;
          color: rgba(20, 114, 255, 1);
          padding: 0 .08rem;
          margin-right: .08rem;
          border-radius: 2px;
        }

        .border-orange {
          border: #FF781F .02rem solid;
          color: rgba(255, 120, 31, 1);
          padding: 0 .08rem;
          border-radius: 2px;
        }
      }

      .goods-selector {
        margin-bottom: .16rem;
      }

      .goods-price {
        display: inline-block;
        margin-right: 0.08rem;
        margin-bottom: .16rem;
        color: #FF5024;
      }
      // 销售单位
      .sale-unit {
        font-size: .24rem;
      }

      .goods-tags {
        display: inline-block;
      }

      .goods-tag {
        display: inline-block;
        padding: 0.02rem 0.12rem;
        font-size: 0.2rem;
        border-radius: 0.2rem;

        &+.goods-tag {
          margin-left: 0.08rem;
        }

        &.marketing-tag {
          color: #FF781F;
          background: #FFF3EB;
        }

        &.send-friend {
          color: #07C160;
          border: 1px solid rgba(7, 193, 96, 0.5);
        }
      }

      .goods-counter {
        flex-shrink: 0;
      }
    }
  }
  </style>
